package com.zzz.security;

import com.zzz.dao.UserDao;
import com.zzz.entity.Permission;
import com.zzz.entity.User;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Chunsheng.Zhang
 * @date 2021/5/11 9:45
 * @description : TODO
 */
@AllArgsConstructor
@Component
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDao;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || username.isEmpty()) {
            throw new UsernameNotFoundException("用户名不能为空");
        }
        //根据用户名从数据库中查询用户信息
        User user = userDao.selByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //根据userId从数据库中查询用户权限
        List<Permission> permissionList = (List)user.getAuthorities();
        //将权限set到user对象中（由于User实现了UserDetails，所以user对象就是一个UserDetails对象）
        user.setPermissionList(permissionList);
        return user;
    }
}
